<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">基本资料</div>
    <!-- 修改用户信息的表单 -->
    <el-form :model="user" :rules="userRules" label-width="80px" style="width: 500px" ref="userRef">
      <!-- 登录名称 -->
      <el-form-item label="登录名称">
        <el-input v-model="user.username" :disabled="true"></el-input>
      </el-form-item>
      <!-- 用户昵称 -->
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="user.nickname"></el-input>
      </el-form-item>
      <!-- 用户邮箱 -->
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <!-- 按钮区域 -->
      <el-form-item>
        <el-button type="primary" @click="updataUserinfo">提交修改</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updataUserAPI } from '@/api/user.js'
export default {
  name: 'UserInfo',
  data() {
    return {
      // 数据对象
      user: Object.assign({}, this.$store.state.user),
      userRules: {
        nickname: [
          { required: true, message: '用户昵称是必填项', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '用户昵称必须是1-10位的非空字符串' }
        ],
        email: [
          { required: true, message: '用户邮箱是必填项', trigger: 'blur' },
          { type: 'email', message: '用户邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updataUserinfo() {
      this.$refs.userRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await updataUserAPI(this.user)
        if (res.code !== 0) return this.$message.error('用户信息更新失败')
        this.$message.success('更新用户信息成功')
        this.$store.dispatch('initUser')
      })
    },
    reset() {
      // 先把表单数据浅拷贝一份，绑定给表单数据，然后在移除修改
      this.user = Object.assign({}, this.$store.state.user)
      // resetFields()是Form表单自带的对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs.userRef.resetFields()
    }
  }
}
</script>

<style lang="less" scoped></style>
